package com.evil.application.strategy.application;

import com.evil.application.pojo.dto.CopyApplicationDTO;
import com.evil.application.pojo.entity.ApplicationInfo;
import com.evil.common.application.enums.ApplicationTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Consumer;

/**
 * 应用操作策略
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
@Component
@AllArgsConstructor
public class ApplicationOperationStrategy {

    private final List<ApplicationOperation> applicationOperationList;

    public void addApplication(ApplicationInfo applicationInfo) {
        this.adaptation(applicationInfo, applicationOperation -> applicationOperation.addApplication(applicationInfo));
    }

    public void deleteApplication(ApplicationInfo applicationInfo) {
        this.adaptation(applicationInfo, applicationOperation -> applicationOperation.deleteApplication(applicationInfo));
    }

    public void copyApplication(ApplicationInfo source, ApplicationInfo target) {
        this.adaptation(source, applicationOperation -> applicationOperation.copyApplication(new CopyApplicationDTO(source, target)));
    }

    public void publishApplication(ApplicationInfo applicationInfo) {
        this.adaptation(applicationInfo, applicationOperation -> applicationOperation.publishApplication(applicationInfo));
    }

    public void restoreApplication(ApplicationInfo applicationInfo) {
        this.adaptation(applicationInfo, applicationOperation -> applicationOperation.restoreApplication(applicationInfo));
    }

    /**
     * 操作 （如果需要返回值则把Consumer参数改成Function）
     *
     * @param applicationInfo applicationInfo
     * @param operation       operation
     */
    private void adaptation(ApplicationInfo applicationInfo, Consumer<ApplicationOperation> operation) {
        for (ApplicationOperation applicationOperation : applicationOperationList) {
            if (applicationOperation.type().getId() == applicationInfo.getApplicationType()) {
                operation.accept(applicationOperation);
                return;
            }
        }
        throw ApplicationTypeEnum.getBusinessException();
    }
}
